'use client'

import { useState, useEffect } from 'react'
import { Button, message } from 'antd'
import { useRouter } from 'next/navigation'
import { useAuth } from '../../contexts/AuthContext'
import UploadForm from '../../components/UploadForm'
import DatabaseStatus from '../../components/DatabaseStatus'
import { FullScreenLoading } from '../../components/LoadingSpinner'
import { handleUploadError, handleApiError, showSuccess } from '../../utils/errorHandler'

export default function UploadPage() {
    const [loading, setLoading] = useState(false)
    const [uploadStep, setUploadStep] = useState('')
    const [uploadSuccess, setUploadSuccess] = useState(false)
    const [uploadedProductId, setUploadedProductId] = useState(null)
    const router = useRouter()
    const { user, isAuthenticated } = useAuth()

    // 检查用户认证状态
    useEffect(() => {
        if (!isAuthenticated) {
            message.warning('请先登录以上传产品')
            router.push('/login')
            return
        }
    }, [isAuthenticated, router])

    // 处理表单提交
    const handleSubmit = async (formData, setUploadProgress) => {
        setLoading(true)
        setUploadProgress(0)

        try {
            setUploadStep('正在准备上传...')
            setUploadProgress(10)

            // 准备 FormData 用于文件上传
            const submitData = new FormData()

            // 添加基本字段
            submitData.append('title', formData.title)
            submitData.append('description', formData.description)
            submitData.append('type', formData.type)

            // 添加用户ID
            if (user?.id) {
                submitData.append('userId', user.id)
            } else {
                throw new Error('用户信息不完整，请重新登录')
            }

            if (formData.url) {
                submitData.append('url', formData.url)
            }

            // 添加文件
            if (formData.file) {
                setUploadStep('正在上传应用文件...')
                setUploadProgress(30)
                submitData.append('file', formData.file)
            }

            if (formData.thumbnail) {
                setUploadStep('正在上传缩略图...')
                setUploadProgress(50)
                submitData.append('thumbnail', formData.thumbnail)
            }

            setUploadStep('正在保存产品信息...')
            setUploadProgress(70)

            // 直接提交到产品创建 API，让后端处理文件上传
            const response = await fetch('/api/products', {
                method: 'POST',
                body: submitData // 使用 FormData，不设置 Content-Type
            })

            const result = await response.json()

            if (!response.ok || !result.success) {
                // 如果是数据库表不存在的错误，提供更友好的提示
                if (result.error?.details?.includes('Could not find the table')) {
                    throw new Error('数据库表尚未创建，请先运行数据库迁移')
                }
                throw new Error(result.error?.message || '提交产品信息失败')
            }

            setUploadProgress(100)
            setUploadStep('上传完成！')
            setUploadSuccess(true)
            setUploadedProductId(result.data?.id)
            showSuccess('产品上传成功', '您的产品已成功添加到平台')

        } catch (error) {
            console.error('上传错误:', error)

            // 根据错误类型使用不同的错误处理器
            if (error.message.includes('文件') || error.message.includes('上传')) {
                handleUploadError(error, formData.file?.name)
            } else {
                handleApiError(error)
            }

            setUploadProgress(0)
            setUploadStep('')
            setUploadSuccess(false)
        } finally {
            setLoading(false)
        }
    }

    // 如果用户未认证，显示加载状态
    if (!isAuthenticated) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <FullScreenLoading visible={true} tip="检查登录状态..." />
            </div>
        )
    }

    return (
        <>
            <div className="p-8">
                <div className="max-w-4xl mx-auto">
                    <h1 className="text-3xl font-bold text-center mb-8">
                        上传产品
                    </h1>
                    <p className="text-center text-gray-600 mb-8">
                        在这里上传您的产品信息，与其他用户分享您的成果。
                    </p>

                    <DatabaseStatus />

                    {/* 成功后的操作界面 */}
                    {uploadSuccess ? (
                        <div className="text-center py-12">
                            <div className="mb-8">
                                <div className="text-6xl mb-4">✅</div>
                                <h2 className="text-2xl font-bold text-green-600 mb-2">上传成功！</h2>
                                <p className="text-gray-600">您的产品已成功添加到平台</p>
                            </div>

                            <div className="flex justify-center gap-4">
                                <Button
                                    type="primary"
                                    size="large"
                                    onClick={() => {
                                        setUploadSuccess(false)
                                        setUploadedProductId(null)
                                        setUploadProgress(0)
                                        setUploadStep('')
                                    }}
                                >
                                    继续上传产品
                                </Button>

                                <Button
                                    size="large"
                                    onClick={() => router.push('/products')}
                                >
                                    返回前页
                                </Button>

                                {uploadedProductId && (
                                    <Button
                                        type="primary"
                                        size="large"
                                        style={{ backgroundColor: '#52c41a', borderColor: '#52c41a' }}
                                        onClick={() => router.push(`/product/${uploadedProductId}`)}
                                    >
                                        查看产品
                                    </Button>
                                )}
                            </div>
                        </div>
                    ) : (
                        <UploadForm onSubmit={handleSubmit} loading={loading} />
                    )}
                </div>
            </div>

            {/* 全屏加载遮罩 */}
            <FullScreenLoading visible={loading} tip={uploadStep || '处理中...'} />
        </>
    )
}